package com.wutao.panzh.interceptor;

import com.panzh.entity.UserAdminInfo;
import com.panzh.util.StringUtil;
import com.panzh.wutao.util.ObjectUtil;
import com.wutao.panzh.coust.WebConst;
import com.wutao.panzh.util.CookieUtil;
import com.wutao.panzh.util.HttpCilentUtil;
import com.wutao.panzh.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.WebConnection;
import java.util.Map;

//咱们这里这给当个系统使用单点登录，所以很简单，不用注解，全部默认拦截即可;
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    //handler请求的mapper地址；
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        StringBuffer url = request.getRequestURL();
//        System.out.println(url);
//        //这里是给一个方法加上注解，使用handler进行统一的拦截处理;
//        HandlerMethod am = (HandlerMethod) handler;
//        Annotation annotation = am.getMethodAnnotation(LoginRequired.class);
//        if (annotation != null){
//            //需要进行登录，直接打回去；
//            response.sendRedirect("http://localhost:8080/index");
//            return false;
//        }
//        return  true;
        String oldToken = CookieUtil.getCookieValue(request, "oldToken", true);
        String newToken = (String) request.getParameter("newToken");

        if (StringUtil.stringCheck(newToken)) {
            oldToken = newToken;
        }
        if (!StringUtil.stringCheck(oldToken)) {
            //咱们直接打回去；打回去重新登录;
            //获取请求的ip地址;
            StringBuffer requestURL = request.getRequestURL();
            response.sendRedirect(WebConst.PANZH_ADMIN_PRIFIX + "index?returnURL=" + requestURL);
            return false;
        } else {
            //这里就是token不空；验证oldToken；
            String result = HttpCilentUtil.doGet(WebConst.PANZH_ADMIN_PRIFIX + "decode?token=" + oldToken);
            if (WebConst.JWT_IS_SECESS.equals(result)) {
                //验证成功
                Map map = JwtUtil.decode(WebConst.WEB_PASSWORD_KEY, oldToken, StringUtil.md5("127.0.0.1"));
                UserAdminInfo userAdminInfo = (UserAdminInfo) ObjectUtil.MapTranfObject(map, UserAdminInfo.class);
                CookieUtil.setCookie(request,response,"oldToken",oldToken,1000,true);
                request.setAttribute("userAdminInfo",userAdminInfo);
                return true;
            }
        }

        return false;
    }
}
